<?php

class post
{
    public static function setName():bool
    {
        $newName = $_POST["newName"];
        setcookie("name", $newName);
        echo "ok";
        return true;
    }

    public static function joinChat():bool
    {
        $roomId = $_POST["roomId"];
        $file = DATA_PATH . $roomId . ".room";
        if (strlen(@file_get_contents($file)) > 0) {
            echo "success";
            setcookie("roomId", $roomId);
            $host = (int)explode(".", $_SERVER['REMOTE_ADDR'])[3];
            if ($host > 200) {
                $host -= 200;
            } elseif ($host > 100) {
                $host -= 100;
            }
            $time = date("H:i");
            $file = DATA_PATH . $roomId . ".room";
            $cfgFile = DATA_PATH . $roomId . ".cfg";
            $cfg = json_decode(encryptTool::decode(file_get_contents($cfgFile),SECRET,true),true);
            setcookie("roomPassword","");
            if ($cfg["enablePassword"]=="yes"){
                echo "password";
                die();
            }
            $counterFile = DATA_PATH . $roomId . ".counter";
            $content = json_decode(encryptTool::decode(file_get_contents($file), SECRET, true),true);
            if ($cfg["joinTip"]=="yes") {
                $content[count($content)] = "<b class='system-message'>$time 【${host}】进入房间</b>";
                file_put_contents($file, (encryptTool::encode(json_encode($content), SECRET, true)));
                $counter = (int)file_get_contents($counterFile);
                $counter += 1;
                file_put_contents($counterFile, $counter);
            }
        } else {
            echo "fail";
        }
        return true;
    }

    public static function createChat():bool
    {
        $roomId = $_POST["roomId"];
        $enablePassword = $_REQUEST["enablePassword"];
        $password = $_REQUEST["password"];
        $file = DATA_PATH . $roomId . ".room";
        $counterFile = DATA_PATH . $roomId . ".counter";
        $cfgFile = DATA_PATH . $roomId . ".cfg";
        $host = (int)explode(".", $_SERVER['REMOTE_ADDR'])[3];
        if ($host > 200) {
            $host -= 200;
        } elseif ($host > 100) {
            $host -= 100;
        }
        if (strlen(@file_get_contents($file)) > 0) {
            echo "fail";
        } else {
            if (touch($file)) {
                touch($counterFile);
                file_put_contents($counterFile, "0");
                file_put_contents($file, encryptTool::encode(json_encode(["<b class='system-message'>欢迎来到${roomId}聊天室</b>","<b class='system-message'>点击下方按钮发送消息</b>"]), SECRET, true));
                file_put_contents($cfgFile,encryptTool::encode(json_encode(["admin"=>$host,"sendPic"=>"yes","joinTip"=>"yes","banList"=>[],"enablePassword"=>$enablePassword,"password"=>$password]),SECRET,true));
                setcookie("roomId", $roomId);
                setcookie("roomPassword",$password);
                echo "success";
            } else {
                echo "fail";
            }
        }
        return true;
    }

    public static function getMessage():bool
    {
        $roomId = $_COOKIE["roomId"];
        $content = encryptTool::decode(file_get_contents(DATA_PATH . $roomId . ".room"), SECRET, true);
        echo $content;
        return true;
    }

    public static function getCounter():bool
    {
        $roomId = $_COOKIE["roomId"];
        $counterFile = DATA_PATH . $roomId . ".counter";
        $counter = (int)file_get_contents($counterFile);
        echo $counter;
        return true;
    }

    public static function sendMessage():bool
    {
        $roomId = $_COOKIE["roomId"];
        $name = $_COOKIE["name"];
        $host = (int)explode(".", $_SERVER['REMOTE_ADDR'])[3];
        if ($host > 200) {
            $host -= 200;
        } elseif ($host > 100) {
            $host -= 100;
        }
        $cfgFile = DATA_PATH . $roomId . ".cfg";
        $config = json_decode(encryptTool::decode(file_get_contents($cfgFile),SECRET,true),true);
        $banList = $config["banList"];
        $code = @$banList["$host"]["code"];
        if ($code=="1"){
            echo "ban";
            die();
        }elseif ($code=="2"){
            echo "ban2";
            die();
        }
        $message = $_POST["message"];
        $message = str_replace("\n","<br>",
            str_replace("#&lt;","<",
                str_replace("<","&lt;",$message)
            )
        );
        $banWord = json_decode(encryptTool::decode(file_get_contents("word.ban"),SECRET,true),true);
        for ($i = 0;$i<count($banWord);$i++){
            $k = array_keys($banWord)[$i];
            $message = str_replace($k,$banWord[$k],$message);
        }
        $colorList = ["blue","green","purple","red","yellow","orange","brown","grey","gray"];
        for ($i = 0;$i < count($colorList);$i++){
            $c = $colorList[$i];
            $message = str_replace("#$c","<b class='message-$c'>",str_replace("$c#","</b>",$message));
        }
        for ($i = 1;$i <= 17;$i++){
            $message = str_replace("#emoji-$i#","<span class='emoji-$i'></span>",$message);
        }
        for ($i = 1;$i < 7;$i++){
            $message = str_replace("#h$i","<b class='text-h$i'>",str_replace("h$i#","</b>",$message));
        }
        $message .= "</b>";
        $time = date("H:i");
        $file = DATA_PATH . $roomId . ".room";
        $counterFile = DATA_PATH . $roomId . ".counter";
        $content = json_decode(encryptTool::decode(file_get_contents($file), SECRET, true),true);
        $content[count($content)] = "$time ${name}【${host}】 ： $message";
        file_put_contents($file, (encryptTool::encode(json_encode($content), SECRET, true)));
        $counter = (int)file_get_contents($counterFile);
        $counter += 1;
        file_put_contents($counterFile, $counter);
        echo "ok";
        return true;
    }

    public static function saveMessage():bool
    {
        $roomId = $_COOKIE["roomId"];
        $content = encryptTool::encode(@$_REQUEST["content"],SECRET,true);
        $file = DATA_PATH . $roomId . ".room";
        $counterFile = DATA_PATH . $roomId . ".counter";
        file_put_contents($file,$content);
        $counter = (int)file_get_contents($counterFile);
        $counter += 1;
        file_put_contents($counterFile, $counter);
        echo "ok";
        return true;
    }

    public static function setColor():bool
    {
        $color = $_REQUEST["color"];
        setcookie("color",$color);
        echo "ok";
        return true;
    }

    public static function getRoomInfo():bool
    {
        $roomId = $_COOKIE["roomId"];
        $cfg = DATA_PATH . $roomId . ".cfg";
        $config = encryptTool::decode(file_get_contents($cfg),SECRET,true);
        echo $config;
        return true;
    }

    public static function getHost():bool
    {
        $host = (int)explode(".", $_SERVER['REMOTE_ADDR'])[3];
        if ($host > 200) {
            $host -= 200;
        } elseif ($host > 100) {
            $host -= 100;
        }
        echo $host;
        return true;
    }

    public static function sendPic():bool
    {
        print_r($_FILES);
        $t = time();
        move_uploaded_file($_FILES["upload-file"]["tmp_name"],"data/files/".$t.".");
        $message = "<img src='./?/file/uploaded&id=$t' alt='图片加载失败' title='图片'>";

        $roomId = $_COOKIE["roomId"];
        $name = $_COOKIE["name"];
        $host = (int)explode(".", $_SERVER['REMOTE_ADDR'])[3];
        if ($host > 200) {
            $host -= 200;
        } elseif ($host > 100) {
            $host -= 100;
        }
        $cfgFile = DATA_PATH . $roomId . ".cfg";
        $config = json_decode(encryptTool::decode(file_get_contents($cfgFile),SECRET,true),true);
        $banList = $config["banList"];
        $code = @$banList["$host"]["code"];
        if ($code=="1"){
            echo "ban";
            die();
        }elseif ($code=="2"){
            echo "ban2";
            die();
        }
        $time = date("H:i");
        $file = DATA_PATH . $roomId . ".room";
        $counterFile = DATA_PATH . $roomId . ".counter";
        $content = json_decode(encryptTool::decode(file_get_contents($file), SECRET, true),true);
        $content[count($content)] = "$time ${name}【${host}】 ： $message";
        file_put_contents($file, (encryptTool::encode(json_encode($content), SECRET, true)));
        $counter = (int)file_get_contents($counterFile);
        $counter += 1;
        file_put_contents($counterFile, $counter);
        echo "ok";
        return true;
    }

    public static function getRoomList():bool
    {
        $a = scandir("data/");
        $b = [];
        foreach ($a as $item) {
            if ($item!="."&&$item!=".."&&$item!="files"){
                if (@explode(".",$item)[1]=="room"){
                    $r = explode(".",$item)[0];
                    $cfgFile = DATA_PATH . $r . ".cfg";
                    $cfg = json_decode(encryptTool::decode(file_get_contents($cfgFile),SECRET,true),true);
                    $b[$r] = ["admin"=>$cfg["admin"],"sendPic"=>$cfg["sendPic"],"joinTip"=>$cfg["joinTip"],"enablePassword"=>$cfg["enablePassword"]];
                }
            }
        }
        echo json_encode($b);
        return true;
    }

    public static function isAdmin($return = false):bool
    {
        @touch("data/config/admin.code");
        $k = file_get_contents("data/config/admin.code");
        if (strlen($k)==0){
            $k = "lDlyAVSEbRcuIIjZAiRUkeUUDwEUCUQkjBslORSyiLtrebAjWmARRYqqbRdrHGeGuMmlQBGqCfVGSanKGdWBqjVbDlCVZGLLtKtyFXgXlOoyDmjJDiFYnfPTrGllEhvweyRzGsVo";
            file_put_contents("data/config/admin.code",$k);
        }
        $c = @$_COOKIE["admin_code"];
        if (strlen($c)!=0) {
            $q = encryptTool::decode($k, $c, true);
            if (!$c) $c = "";
            $v = $q == $c ? "yes" : "no";
            /*core::log($c."\n");
            core::log($q);*/
        }else{
            $v = "no";
        }
        if ($return) {
            return $v;
        }else {
            echo $v;
        }
        return true;
    }

    public static function ban():bool
    {
        $id = @$_REQUEST["id"];
        $host = (int)explode(".", $_SERVER['REMOTE_ADDR'])[3];
        if ($host > 200) {
            $host -= 200;
        } elseif ($host > 100) {
            $host -= 100;
        }
        $roomId = @$_COOKIE["roomId"];
        $cfgFile = DATA_PATH . $roomId . ".cfg";
        $cfg = json_decode(encryptTool::decode(file_get_contents($cfgFile),SECRET,true),true);
        if ((string)$cfg["admin"] == $host || self::isAdmin(true)){
            $time = date("H:i");
            $cfg["banList"]["$id"] = ["code"=>"1","time"=>$time];
            file_put_contents($cfgFile,encryptTool::encode(json_encode($cfg),SECRET,true));


            $file = DATA_PATH . $roomId . ".room";
            $counterFile = DATA_PATH . $roomId . ".counter";
            $content = json_decode(encryptTool::decode(file_get_contents($file), SECRET, true),true);
            $adminFlag = self::isAdmin(true)=="yes"?"超级管理员":"房间管理员";
            $content[count($content)] = "<b class='system-message'>【${id}】已被${adminFlag}禁言</b>";
            file_put_contents($file, (encryptTool::encode(json_encode($content), SECRET, true)));
            $counter = (int)file_get_contents($counterFile);
            $counter += 1;
            file_put_contents($counterFile, $counter);
            echo "ok";
        }else{
            echo "no-admin";
        }
        return true;
    }

    public static function unban():bool
    {
        $id = @$_REQUEST["id"];
        $host = (int)explode(".", $_SERVER['REMOTE_ADDR'])[3];
        if ($host > 200) {
            $host -= 200;
        } elseif ($host > 100) {
            $host -= 100;
        }
        $roomId = @$_COOKIE["roomId"];
        $cfgFile = DATA_PATH . $roomId . ".cfg";
        $cfg = json_decode(encryptTool::decode(file_get_contents($cfgFile),SECRET,true),true);
        if ((string)$cfg["admin"] == $host || self::isAdmin(true)){
            unset($cfg["banList"]["$id"]);
            file_put_contents($cfgFile,encryptTool::encode(json_encode($cfg),SECRET,true));


            $file = DATA_PATH . $roomId . ".room";
            $counterFile = DATA_PATH . $roomId . ".counter";
            $content = json_decode(encryptTool::decode(file_get_contents($file), SECRET, true),true);
            $adminFlag = self::isAdmin(true)=="yes"?"超级管理员":"房间管理员";
            $content[count($content)] = "<b class='system-message'>【${id}】已被${adminFlag}解除禁言</b>";
            file_put_contents($file, (encryptTool::encode(json_encode($content), SECRET, true)));
            $counter = (int)file_get_contents($counterFile);
            $counter += 1;
            file_put_contents($counterFile, $counter);
            echo "ok";
        }else{
            echo "no-admin";
        }
        return true;
    }

    public static function setRoomCfg():bool
    {
        $canSend = @$_REQUEST["canSend"];
        $joinTip = @$_REQUEST["joinTip"];
        $roomId = @$_COOKIE["roomId"];
        $host = (int)explode(".", $_SERVER['REMOTE_ADDR'])[3];
        if ($host > 200) {
            $host -= 200;
        } elseif ($host > 100) {
            $host -= 100;
        }
        $cfgFile = DATA_PATH . $roomId . ".cfg";
        $cfg = json_decode(encryptTool::decode(file_get_contents($cfgFile),SECRET,true),true);
        if ((string)$cfg["admin"] == $host || self::isAdmin(true)){
            $file = DATA_PATH . $roomId . ".room";
            $counterFile = DATA_PATH . $roomId . ".counter";
            $content = json_decode(encryptTool::decode(file_get_contents($file), SECRET, true),true);
            $adminFlag = self::isAdmin(true)=="yes"?"超级管理员":"房间管理员";
            $update = false;
            if ($cfg["sendPic"]!=$canSend) {
                $cfg["sendPic"] = $canSend;
                $allowFlag = $canSend == "yes" ? "允许" : "禁止";
                $content[count($content)] = "<b class='system-message'>${adminFlag}已${allowFlag}房间发送图片</b>";
                $update = true;
            }
            if ($cfg["joinTip"]!=$joinTip){
                $cfg["joinTip"]=$joinTip;
                $allowFlag = $joinTip == "yes" ? "开启" : "关闭";
                $content[count($content)] = "<b class='system-message'>${adminFlag}${allowFlag}加入聊天室提示</b>";
                $update = true;
            }
            file_put_contents($cfgFile,encryptTool::encode(json_encode($cfg),SECRET,true));


            if ($update) {
                file_put_contents($file, (encryptTool::encode(json_encode($content), SECRET, true)));
                $counter = (int)file_get_contents($counterFile);
                $counter += 1;
                file_put_contents($counterFile, $counter);
            }
            echo "ok";
        }else{
            echo "no-admin";
        }
        return true;
    }

    public static function deleteRoom():bool
    {
        $roomId = @$_REQUEST["id"];
        unlink(DATA_PATH.$roomId.".room");
        unlink(DATA_PATH.$roomId.".cfg");
        unlink(DATA_PATH.$roomId.".counter");
        return true;
    }

    public static function getBanIPList():bool
    {
        encryptTool::decode(file_get_contents("ip.ban"),SECRET);
        return true;
    }

    public static function setBanIP()
    {
        if (self::isAdmin(true)=="yes") {
            $a = json_decode(encryptTool::decode(file_get_contents("ip.ban"), SECRET, true), true);
            $ip = str_replace(" ","",@$_REQUEST["ip"]);
            $code = str_replace(" ","",@$_REQUEST["code"]);
            $a[$ip] = ["code" => $code];
            file_put_contents("ip.ban", encryptTool::encode(json_encode($a), SECRET, true));
            echo "ok";
        }else{
            echo "no-admin";
        }
        return true;
    }

    public static function unbanIP():bool
    {
        if (self::isAdmin(true)=="yes") {
            $a = json_decode(encryptTool::decode(file_get_contents("ip.ban"), SECRET, true), true);
            $ip = @$_REQUEST["ip"];
            unset($a[$ip]);
            file_put_contents("ip.ban", encryptTool::encode(json_encode($a), SECRET, true));
            echo "ok";
        }else{
            echo "no-admin";
        }
        return true;
    }

    public static function getBanWordList():bool
    {
        encryptTool::decode(file_get_contents("word.ban"),SECRET);
        return true;
    }

    public static function setBanWord():bool
    {
        if (self::isAdmin(true)=="yes") {
            $a = json_decode(encryptTool::decode(file_get_contents("word.ban"), SECRET, true), true);
            $ip = (string)@$_REQUEST["ip"];
            $code = @$_REQUEST["code"];
            $a["$ip"] = $code;
            file_put_contents("word.ban", encryptTool::encode(json_encode($a), SECRET, true));
            echo "ok";
        }else{
            echo "no-admin";
        }
        return true;
    }

    public static function unbanWord():bool
    {
        if (self::isAdmin(true)=="yes") {
            $a = json_decode(encryptTool::decode(file_get_contents("word.ban"), SECRET, true), true);
            $ip = (string)@$_REQUEST["ip"];
            unset($a[$ip]);
            file_put_contents("word.ban", encryptTool::encode(json_encode($a), SECRET, true));
            echo "ok";
        }else{
            echo "no-admin";
        }
        return true;
    }

    public static function getIPVisitorList():bool
    {
        $cfg = json_decode(encryptTool::decode(file_get_contents("data/config/global.cfg"),SECRET,true),true);
        $encrypt = $cfg["enableLogIPEncrypt"]=="yes";
        $fn = "data/config/visitor.log";
        if ($encrypt) {
            $a = json_decode(encryptTool::decode(file_get_contents($fn), SECRET, true), true);
        }else{
            $a = json_decode(file_get_contents($fn),true);
        }
        $b = [];
        for ($i = 0;$i<count($a);$i++){
            $k = array_keys($a)[$i];
            $v = $a[$k];
            $b[$k] = count(array_keys($v));
        }
        echo json_encode($b);
        return true;
    }

    public static function getIPVisitData():bool
    {
        $cfg = json_decode(encryptTool::decode(file_get_contents("data/config/global.cfg"),SECRET,true),true);
        $encrypt = $cfg["enableLogIPEncrypt"]=="yes";
        $fn = "data/config/visitor.log";
        $IP = @$_REQUEST["IP"];
        if($encrypt) {
            $a = json_decode(encryptTool::decode(file_get_contents($fn), SECRET, true), true)[$IP];
        }else{
            $a = json_decode(file_get_contents($fn),true);
        }
        echo json_encode($a);
        return true;
    }

    public static function settings():bool
    {
        if (true){
            $action = @$_REQUEST["action"];
            $content = @$_REQUEST["content"];
            $configName = "data/config/global.cfg";
            $logIPName = "data/config/visitor.log";
            $adminCodeName = "data/config/admin.code";
            $config = json_decode(encryptTool::decode(file_get_contents($configName),SECRET,true),true);

            switch ($action){
                case "getSettings":
                    echo json_encode($config);
                    die();
                case "setEnableLogIP":
                    $config["enableLogIP"] = $content;
                    if ($content=="no"){
                        $config["enableLogIPEncrypt"] = "no";
                    }
                    break;
                case "setEnableLogIPEncrypt":
                    $config["enableLogIPEncrypt"] = $content;
                    $a = file_get_contents($logIPName);
                    if ($content=="yes"){
                        $a = encryptTool::encode($a,SECRET,true);
                    }else{
                        $a = encryptTool::decode($a,SECRET,true);
                    }
                    file_put_contents($logIPName,$a);
                    break;
                case "cleanLogIP":
                    if ($config["enableLogIPEncrypt"]=="yes"){
                        $x = json_encode([]);
                    }else{
                        $x = encryptTool::encode(json_encode([]),SECRET,true);
                    }
                    die(file_put_contents($logIPName,$x) ? "ok":"error");
                case "setAdminPassword":
                    $a = encryptTool::encode($content,$content,true);
                    setcookie("admin_code",$content);
                    die(file_put_contents($adminCodeName,$a)?"ok":"error");
                default:
                    die("unknown");
            }
            echo file_put_contents($configName,encryptTool::encode(json_encode($config),SECRET,true)) ? "ok":"error";
        }else{
            echo "no-admin";
        }
        return true;
    }
}